/*
 *太原学院计算机科学与技术系（C）版权所有
 * @author liyanrong
 * @version 1.0
 */
package cn.edu.tyu.finance.thingstype.servlet;

import cn.edu.tyu.util.DbUtil;
import cn.edu.tyu.util.StringUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.*;
import jakarta.servlet.annotation.*;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * 添加用户
 * @author liyanrong
 */
@WebServlet(name = "AddUserServlet", value = "/AddUserServlet")
public class AddUserServlet extends HttpServlet {
    @Override
    /**
     * 处理网页发来的get请求
     * @param request 请求对象
     * @param response 响应对象
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uname = request.getParameter("username");
        String upsw = request.getParameter("userpsw");
        String upswMD5 = StringUtil.getMD5(upsw);
//2.连接数据库把接收到的数据写入表里
        Connection conn = null;
        PreparedStatement pstmt = null;
        conn = DbUtil.getConnection();
        int flag = 0;
        String sql = "INSERT INTO users VALUES(?,?,?)";
        try {
            pstmt = conn.prepareStatement(sql);
            pstmt.setString(1,(int)(Math.random()*1000) + "");
            pstmt.setString(2,uname);
            pstmt.setString(3,upswMD5);
            flag = pstmt.executeUpdate();//下达执行指令
            if (flag == 0){
                response.sendRedirect("fail,jsp");
            } else{
                response.sendRedirect("ok.jsp");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
//3，关闭数据库资源
        DbUtil.backConn(conn,pstmt,null);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}
